const db = uniCloud.database();
const dbCmd = db.command;
module.exports = {
  _before: function () {
    // 通用预处理器
  },
  async whriteDownload({ picid, classid } = {}) {
    if (!picid || !classid) {
      return {
        errCode: 400,
        errMsg: "参数不能为空",
      };
    }
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    dbJQL
      .collection("dc-bizhi-piclist")
      .doc(picid)
      .update({
        download_count: dbCmd.inc(1),
      });

    let { total } = await dbJQL
      .collection("dc-bizhi-download")
      .where(`picid == "${picid}" && user_id == $cloudEnv_uid`)
      .count();
    if (total > 0) {
      return await dbJQL
        .collection("dc-bizhi-download")
        .where(`picid == "${picid}" && user_id == $cloudEnv_uid`)
        .update({
          createTime: Date.now(),
        });
    }
    return await dbJQL.collection("dc-bizhi-download").add({
      picid,
      classid,
    });
  },
  async setupScore({ picid, classid, userScore } = {}) {
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    if (!picid || !classid || !userScore) {
      return {
        errCode: 400,
        errMsg: "参数不能为空",
      };
    }

    //userScore需要为数字类型
    if (isNaN(userScore)) {
      return {
        errCode: 400,
        errMsg: "userScore需要为数字类型",
      };
    }
    userScore = Number(userScore); //
    userScore = Math.min(5, Math.max(1, userScore));

    // 查询是否已经评分
    let { total } = await dbJQL
      .collection("dc-bizhi-score")
      .where(`picid == "${picid}" && user_id == $cloudEnv_uid`)
      .count();
    if (total > 0) {
      return {
        errCode: 400,
        errMsg: "您已经评分过了",
      };
    }

    // 计算评分
    let { data } = await dbJQL
      .collection("dc-bizhi-score")
      .where(`picid == "${picid}" && classid == "${classid}"`)
      .get();
    let score = 0;
    for (let i = 0; i < data.length; i++) {
      score += Number(data[i].userScore);
    }
    score += userScore;
    score = score / (data.length + 1);
    score = score.toFixed(1);
    // 更新评分
    dbJQL
      .collection("dc-bizhi-piclist")
      .doc(picid)
      .update({
        score: score.toString(),
        score_count: dbCmd.inc(1),
      });

    return await dbJQL.collection("dc-bizhi-score").add({
      picid,
      classid,
      userScore: userScore.toString(),
    });
  },
  async userScore(picid = "") {
    if (!picid) {
      return {
        errCode: 400,
        errMsg: "参数不能为空",
      };
    }
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    let { data: { userScore = "" } = {} } = await dbJQL
      .collection("dc-bizhi-score")
      .where(`picid == "${picid}" && user_id == $cloudEnv_uid`)
      .field("_id,userScore")
      .orderBy("createTime,desc")
      .get({
        getOne: true,
      });
    return userScore;
  },
  async userHistoryCount() {
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    let p1 = dbJQL
      .collection("dc-bizhi-download")
      .where(`user_id == $cloudEnv_uid`)
      .count();
    let p2 = dbJQL
      .collection("dc-bizhi-score")
      .where(`user_id == $cloudEnv_uid`)
      .count();

    let [r1, r2] = await Promise.all([p1, p2]);
    return {
      downloadSize: r1.total || 0,
      scoreSize: r2.total || 0,
    };
  },
  async userHistoryList({ pageSize = 9, pageNum = 1, type = "" } = {}) {
    if (!type) {
      return {
        errCode: 400,
        errMsg: "参数不能为空",
      };
    }
    pageSize = Math.min(pageSize, 20);
    let skip = (pageNum - 1) * pageSize;
    let tablename =
      type == "download"
        ? "dc-bizhi-download"
        : type == "score"
        ? "dc-bizhi-score"
        : "";
    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo(),
    });
    let tableTemp = dbJQL
      .collection(tablename)
      .where(`user_id == $cloudEnv_uid`)
      .orderBy("createTime,desc")
      .skip(skip)
      .limit(pageSize)
      .getTemp();

    let classTemp = dbJQL
      .collection("dc-bizhi-classify")
      .field("_id,name")
      .getTemp();

    let picTemp = dbJQL
      .collection("dc-bizhi-piclist")
      .field(
        `_id,checked,classid,picurl,score,description,view_count,user_id,tabs`
      )
      .getTemp();
    let res = await dbJQL
      .collection(tableTemp, classTemp, picTemp)
      .field(
        `userScore,
        classid._id as classid,
     classid.name as classname,
      picid._id as _id,
      picid.description as description,
      picid.picurl as picurl,
      picid.score as score,
      picid.tabs as tabs,
      picid.view_count as view_count,
      picid.user_id as user_id
     `
      )
      .get();
    let data = res.data.map((item) => {
      return {
        ...item,
        classname: item.classname[0],
        classid: item.classid[0],
        _id: item._id[0],
        description: item.description[0],
        picurl: item.picurl[0],
        score: item.score[0],
        tabs: item.tabs[0],
        view_count: item.view_count[0],
        user_id: item.user_id[0],
      };
    });

    return { ...res, data };
  },
};
